<template>
  <div class="app-container">
    <div class="title-btns">
      <span class="role-span"><span></span>用户列表</span>
      <div style="float: right">
        <!-- 新增 -->
        <el-button v-permission="['ADMIN','USER_ALL','USER_CREATE']" class="filter-item" size="mini" type="primary" icon="el-icon-plus" @click="toAdd">新增</el-button>

        <el-button v-permission="['ADMIN','USER_ALL','USER_EDIT']" class="filter-item" size="mini" :disabled="multipleSelection.length !== 1" icon="el-icon-edit" type="primary" @click="toUpdate()">修改</el-button>

        <!-- 导出 -->
        <el-button v-permission="['ADMIN','USER_ALL','USER_SELECT']" :loading="downloadLoading" size="mini" class="filter-item" type="primary" icon="el-icon-download" @click="exportExcel">导出</el-button>

      </div>
    </div>

    <div class="head-container">

      <!-- 搜索 -->
      <div class="head-search">
        <el-select v-model="query.type" clearable placeholder="查找类型" class="filter-item" style="width: 130px">
          <el-option v-for="item in queryTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <el-input v-model="query.value" clearable placeholder="输入关键字搜索" style="width: 200px;" class="filter-item" @keyup.enter.native="toQuery" />
        <el-select v-model="query.types" clearable placeholder="用户类型" class="filter-item" style="width: 130px" @change="toQuery">
          <el-option v-for="item in dictobj['user_type_status']" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select v-model="query.sex" clearable placeholder="性别" class="filter-item" style="width: 90px" @change="toQuery">
          <el-option v-for="item in dictobj['sex_status']" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select v-model="query.status" clearable placeholder="状态" class="filter-item" style="width: 90px" @change="toQuery">
          <el-option v-for="item in dictobj['status']" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button class="filter-item" size="mini" type="primary" icon="el-icon-search" @click="toQuery">搜索</el-button>
        <el-button class="filter-item" size="mini" icon="el-icon-refresh" @click="toReSet">重置</el-button>
      </div>
      <!--表格渲染-->
      <el-table v-loading="loading" highlight-current-row :data="data" size="small" style="width: 100%;" @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55"
          align="center"
        />
        <el-table-column prop="nickname" label="姓名" align="center" />
        <el-table-column prop="username" label="用户名" align="center" />
        <el-table-column prop="phone" label="电话" align="center" />
        <el-table-column :show-overflow-tooltip="true" prop="email" label="邮箱" align="center" />
        <el-table-column label="性别" align="center">
          <template slot-scope="scope">
            <div v-for="item in dictobj['sex_status']" :key="item.id">
              <template v-if="scope.row.sex.toString() === item.value" :type="scope.row.sex ? '' : 'info'">{{ item.label }}</template>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <div v-for="item in dictobj['status']" :key="item.id">
              <template v-if="scope.row.status.toString() === item.value" :type="scope.row.status ? '' : 'info'">{{ item.label }}</template>
            </div>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" prop="createDate" label="创建日期" align="center">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户类型" align="center">
          <template slot-scope="scope">
            <div v-for="item in dictobj['user_type_status']" :key="item.id">
              <template v-if="scope.row.type.toString() === item.value" :type="scope.row.type ? '' : 'info'">{{ item.label }}</template>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="checkPermission(['ADMIN','USER_ALL','USER_EDIT','USER_DELETE'])" label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button v-permission="['ADMIN','USER_ALL','USER_EDIT']" size="mini" type="text" @click="toUpdate(scope.row)">修改</el-button>
            <el-popover v-if="scope.row.username !== 'admin'" :ref="scope.row.id" v-permission="['ADMIN','USER_ALL','USER_DELETE']" placement="top" width="180">
              <p>确定{{ scope.row.status=='1'?'停用':'激活' }}该用户吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
                <el-button :loading="delLoading" type="primary" size="mini" @click="enabled(scope.row.id,scope.row.status)">确定</el-button>
              </div>
              <el-button slot="reference" type="text" size="mini" style="margin-left:10px">{{ scope.row.status =='1'?'停用':'激活' }}</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-pagination :total="total" :current-page="page" style="margin-top: 8px;" layout="total, sizes, prev, pager, next, jumper" @size-change="sizeChange" @current-change="pageChange" />
    </div>

    <!-- </el-col>
    </el-row>-->
    <eForm ref="form" :is-add="isAdd" :dictobj="dictobj" />
  </div>
  <!-- -->
</template>

<script>
import checkPermission from '@/utils/permission'
import initData from '@/mixins/initData'
import initDict from '@/mixins/initDict'
import eForm from './module/form'
import {
  enabled, exportExcel
} from '@/api/system/user'
import {
  parseTime
} from '@/utils/index'
// import eHeader from './module/header'
// import edit from './module/edit'
export default {
  components: {
    eForm
  },
  // 初始化数据要用到的
  mixins: [initData, initDict],
  data() {
    return {
      downloadLoading: false,
      queryTypeOptions: [{
        key: 'username',
        display_name: '用户名'
      },
      {
        key: 'nickname',
        display_name: '姓名'
      },
      {
        key: 'email',
        display_name: '邮箱'
      },
      {
        key: 'phone',
        display_name: '电话号'
      }
      ],
      enabledTypeOptions: [{
        key: '0',
        display_name: '启用'
      },
      {
        key: '1',
        display_name: '停用'
      }
      ],
      height: document.documentElement.clientHeight - 180 + 'px;',
      delLoading: false,
      sup_this: this,
      deptName: '',
      depts: [],
      deptId: null,
      dictobj: {},
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      multipleSelection: []
    }
  },
  // 页面初始化数据
  created() {
    this.getDictObj('status,user_type_status,sex_status')
    setTimeout(() => {
      this.$nextTick(() => {
        this.init()
      })
    }, 500)
  },
  mounted: function() {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
  },
  methods: {
    parseTime,
    checkPermission,
    /**
     * 初始化数据前调用
     */
    beforeInit() {
      this.url = 'system/users'
      const sort = 'DESC'
      const sortColumn = 'id'
      const query = this.query
      const type = query.type
      const value = query.value
      const status = query.status
      const sex = query.sex
      const types = query.types
      this.params = {
        page: this.page,
        size: this.size,
        sortColumn: sortColumn,
        sort: sort
      }
      if (type && value) {
      //  this.params[type] = value
        this.params['searchKey'] = type
        this.params['searchValue'] = value
      }
      if (types) {
        this.params['type'] = types
      }
      if (sex) {
        this.params['sex'] = sex
      }
      if (status !== '' && status !== null) {
        this.params['status'] = status
      }
      if (type === 'phone') {
        const result = !isNaN(value)
        if (!result) {
          this.$notify({
            title: '电话填写错误',
            type: 'error',
            duration: 2500
          })
        }
        return result
      }
      return true
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
      console.info(this.multipleSelection)
    },
    /**
    * 去新增
    */
    toAdd() {
      this.isAdd = true
      this.$refs.form.getRoles()
      this.$refs.form.resetForm()
      this.$refs.form.dialog = true
    },

    /**
     * 去修改数据
     */
    toUpdate(data) {
      if (!data) {
        data = this.multipleSelection[0]
      }
      this.isAdd = false
      const _this = this.$refs.form
      _this.getRoles()
      _this.roleIds = []
      _this.form = { id: data.id, username: data.username, nickname: data.nickname, sex: data.sex.toString(), type: data.type, phone: data.phone, email: data.email, status: data.status.toString(), roles: [] }
      data.roles.forEach(function(data, index) {
        _this.roleIds.push(data.id)
      })
      _this.dialog = true
    },

    /**
     * 切换状态
     */
    enabled(id, status) {
      let state = 0
      if (status.toString() === '0') {
        state = 1
      }
      enabled({ id: id, status: state }).then(res => {
        this.$refs[id].doClose()
        this.init()
        this.$notify({
          title: '操作成功',
          type: 'success',
          duration: 2500
        })
      }).catch(err => {
        this.delLoading = false
        this.$refs[id].doClose()
        console.log(err.response.data.message)
      })
    },

    // 导出文件
    exportExcel() {
      exportExcel(this.params).then(response => {
        const filename = '用户数据.xls'
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          window.navigator.msSaveOrOpenBlob(response, filename)
        } else {
          var link = document.createElement('a')
          var blob = new Blob([response])
          link.download = filename
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click() // 执行下载
          URL.revokeObjectURL(link.href) // 释放url
          document.body.removeChild(link) // 释放标签
        }
      })
    }

  }
}
</script>

<style scoped>

</style>
